package top.dotgo.web.admin.oauth.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.dotgo.kit.Const;
import top.dotgo.model.sys.SysAccountEntity;
import top.dotgo.model.sys.dto.SysAccountDTO;
import top.dotgo.service.sys.ISysAccountService;
import top.dotgo.web.admin.oauth.bean.UserDetailBean;
import top.dotgo.web.admin.oauth.service.IUserDetailsService;

/**
 * @author jornl
 * @date 2020/2/23 18:54 星期日
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements IUserDetailsService {

    private final ISysAccountService accountService;

    public UserDetailsServiceImpl(ISysAccountService accountService) {
        this.accountService = accountService;
    }

    public static void main(String[] args) {
        PasswordEncoder encoder = new BCryptPasswordEncoder();

        System.out.println(encoder.encode("admin"));

    }

    @Override
    public UserDetails loadUserByUsername(String userName) {
        //先 通过 手机号登陆
        SysAccountDTO account = accountService.findFirst(new SysAccountDTO().setMobile(userName));
        //再通过 用户名登录
        if (account == null) {
            account = accountService.findFirst(new SysAccountDTO().setUserName(userName));
        }
        //账号没找到
        if (account == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //禁止登陆
        if (!account.getStatus().equals(Const.Status.acc.ENABLE.v)) {
            throw new LockedException("账号禁止登陆");
        }

        UserDetailBean userDetails = new UserDetailBean();
        userDetails.setUsername(userName);
        userDetails.setPassword(account.getPassword());
        userDetails.setId(account.getAccId().toString());

        return userDetails;
    }
}
